/**
 * Copyright (c) 2015-2018, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.manage.controller.module.news;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.base.kit.StrExtKit;
import cn.hg.jfsa.core.SessionThreadLocal;
import cn.hg.jfsa.manage.controller.module.news.validator.NewsValidator;
import cn.hg.jfsa.manage.service.NewsService;
import cn.hg.jfsa.manage.web.LayuiPage;
import cn.hg.jfsa.model.JfsaAdmin;
import cn.hg.jfsa.model.News;
import cn.hg.jfsa.web.theme.ThemeManager;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import java.sql.SQLException;
import java.util.Date;
import java.util.Random;

/**
 * @author Golly
 *
 */
public class NewsController extends BaseController {

	/**
	 * 新闻服务
	 */
	@Inject
	public static NewsService newsService;

	/**
	 * 跳转到列表页面
	 */
	@Before(CacheInterceptor.class)
	@CacheName("news")
	public void index() {
		this.setAttr("newsCategoryList", newsService.getNewsCategoryList());
	}

	/**
	 * Ajax方式查询
	 */
	@Before(CacheInterceptor.class)
	@CacheName("news")
	public void ajaxSearch() {
		// 建立查询键值对
		Kv para = Kv.by("title", this.getPara("title"))
				.set("categoryId", this.getPara("categoryId"))
				.set("status", this.getPara("status"))
				.set("sortField", StrExtKit.humpToUnderline(this.getPara("sortField")))
				.set("sortType", this.getPara("sortType"))
				.set("theme", ThemeManager.me().getCurrentTheme().getId());

		// 通过SQL模板引擎构建SQL及参数
		SqlPara sqlPara = Db.getSqlPara("module.findNews", para);

		// 执行查询
		Page<News> page = News.DAO.paginate(getParaToInt("page"), getParaToInt("limit"), sqlPara);

		// 返回Ajax调用的Json结果
		this.renderJson(new LayuiPage(page));
	}

	/**
	 * 跳转到新增页面
	 */
	public void add() {
		this.setAttr("newsCategoryList", newsService.getNewsCategoryList());

		// 创建一个新的记录并传给前端页面
		this.setAttr("news",
				new News().setHits(0).setBaseHits(Math.abs(new Random().nextInt() % 1000)).setStatus("off"));
	}

	/**
	 * 跳转到编辑页面
	 */
	public void edit() {
		this.setAttr("newsCategoryList", newsService.getNewsCategoryList());

		// 通过ID取得记录并传给前端页面
		this.setAttr("news", News.DAO.findById(this.getParaToInt("id")));
	}

	/**
	 * Ajax方式新建或更新记录
	 */
	@Before({NewsValidator.class, EvictInterceptor.class})
	@CacheName("news")
	public void ajaxSaveOrUpdate() {
		// 获取页面传入的Bean
		News bean = this.getBean(News.class, "news");

		JfsaAdmin admin = SessionThreadLocal.getAdmin();

		// 这里引用事务处理是为了方便Ajax模式处理
		Db.tx(new IAtom() {
			public boolean run() throws SQLException {
				if (null == bean.getId()) {
					// 新建记录
					bean.setTheme(ThemeManager.me().getCurrentTheme().getId())
							.setCreatedTime(new Date())
							.setCreatorId(admin.getId())
							.setEditedTime(new Date())
							.setEditorId(admin.getId())
							.save();
				} else {
					// 更新记录
					bean.setEditorId(admin.getId())
							.setEditedTime(new Date())
							.update();
				}
				return true;
			}
		});

		// 返回Ajax成功
		this.renderAjaxSuccessed();
	}

	/**
	 * Ajax删除功能
	 */
	@Before(EvictInterceptor.class)
	@CacheName("news")
	public void ajaxDel() {
		// 通过页面传入的ID查找到记录
		News bean = News.DAO.findById(this.getParaToInt("id"));

		// 记录不存在则报错
		if (null == bean) {
			this.renderAjaxFailed("1", "记录不存在！");
			return;
		}

		// 更新记录的状态为删除
		bean.setStatus("del").update();

		// 返回Ajax成功
		this.renderAjaxSuccessed();
	}

	/**
	 * 跳转到查看页面
	 */
	@Before(CacheInterceptor.class)
	@CacheName("news")
	public void view() {
		// 通过ID取得记录并传给前端页面
		this.setAttr("news", News.DAO.findById(this.getParaToInt("id")));
	}
}
